package com.hbpu.encap.socket.homework;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class Homework01Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        try {
            System.out.println("等待连接.....");
            Socket accept = serverSocket.accept();
            System.out.println("连接成功：" + accept.getClass());
            try {
                System.out.println("开始接收消息.......");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
                String s = bufferedReader.readLine();
                System.out.println(s);
                try {
                    if (s.equals("name")) {
                        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
                        bufferedWriter.write("我是nova");
                        bufferedWriter.newLine();
                        bufferedWriter.flush();
                    }
                    if (s.equals("hobby")) {
                        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
                        bufferedWriter.write("编写Java程序");
                        bufferedWriter.newLine();
                        bufferedWriter.flush();
                    }
                    System.out.println("发送成功！");
                } catch (IOException e) {
                    System.out.println("回复消息时出现错误：" + e.getMessage());
                }
            } catch (IOException e) {
                System.out.println("接收消息时出现错误：" + e.getMessage());
            }

        } catch (IOException e) {
            System.out.println("连接时出现错误：" + e.getMessage());
        }
        serverSocket.close();


    }
}
